//
//  XDHttpTool.m
//  XDEducation
//
//  Created by apple on 2017/4/6.
//  Copyright © 2017年 apple. All rights reserved.
//

#import "XDHttpTool.h"
#import "AFHTTPSessionManager.h"

@implementation XDHttpTool
/**
 url中不带参数  params带参数的POST网络请求
 
 @param url 请求的url
 @param params 请求参数
 @param success 成功block
 @param failure 失败block
 @return nil
 */
+(NSURLSessionDataTask *)post:(NSString *)url params:(NSDictionary *)params success:(void (^)(id))success failure:(void (^)(NSError *))failure
{
    
    url = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    //1.获得请求管理者
    AFHTTPSessionManager *mgr = [AFHTTPSessionManager manager];
    //    mgr.requestSerializer = [AFJSONRequestSerializer serializer];
    //    mgr.responseSerializer = [AFJSONResponseSerializer serializer];
    //
    mgr.requestSerializer.timeoutInterval = 15;
    //    mgr.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/plain", @"text/html", nil];
    //    [mgr.requestSerializer setValue:@"application/x-www-form-urlencoded; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
    NSURLSessionDataTask *dataTask = [mgr POST:url parameters:params progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        if (success) {
            success(responseObject);
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        if (failure) {
            failure(error);
        }
    }];
    
    return dataTask;
}



+(NSURLSessionDataTask *)post:(NSString *)url authCode:(NSString *)authCode params:(NSDictionary *)params success:(void (^)(id))success failure:(void (^)(NSError *))failure
{
    
    url = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    //1.获得请求管理者
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];

    [manager.requestSerializer setValue:authCode forHTTPHeaderField:@"auth"];
    
    NSURLSessionDataTask *dataTask = [manager POST:url parameters:params progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        [MBProgressHUD hideHUD];
        if (success) {
            success(responseObject);
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        [MBProgressHUD hideHUD];
        if (failure) {
            failure(error);
        }
    }];
    
    return dataTask;
}



+(NSURLSessionDataTask *)get:(NSString *)url params:(NSDictionary *)params success:(void (^)(id))success failure:(void (^)(NSError *))failure{
    
    
    
    url = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    //1.获得请求管理者
    AFHTTPSessionManager *mgr = [AFHTTPSessionManager manager];
    mgr.requestSerializer = [AFJSONRequestSerializer serializer];
    mgr.responseSerializer = [AFJSONResponseSerializer serializer];
    
    mgr.requestSerializer.timeoutInterval = 15;
    mgr.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/plain", @"text/html", nil];
    [mgr.requestSerializer setValue:@"application/x-www-form-urlencoded; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
    NSURLSessionDataTask *dataTask = [mgr GET:url parameters:params progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [MBProgressHUD hideHUD];
        if (success) {
            success(responseObject);
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [MBProgressHUD hideHUD];
        if (failure) {
            failure(error);
        }
    }];
    
    return dataTask;
    
}


+(NSURLSessionDataTask *)get:(NSString *)url authCode:(NSString *)authCode params:(NSDictionary *)params success:(void (^)(id))success failure:(void (^)(NSError *))failure{
    
    
    
    url = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    //1.获得请求管理者
    AFHTTPSessionManager *mgr = [AFHTTPSessionManager manager];
    mgr.requestSerializer = [AFJSONRequestSerializer serializer];
    mgr.responseSerializer = [AFJSONResponseSerializer serializer];
    
    mgr.requestSerializer.timeoutInterval = 15;
    mgr.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/plain", @"text/html", nil];
    [mgr.requestSerializer setValue:@"application/x-www-form-urlencoded; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
    [mgr.requestSerializer setValue:authCode forHTTPHeaderField:@"auth"];
    
    NSURLSessionDataTask *dataTask = [mgr GET:url parameters:params progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [MBProgressHUD hideHUD];
        if (success) {
            success(responseObject);
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [MBProgressHUD hideHUD];
        if (failure) {
            failure(error);
        }
    }];
    
    return dataTask;
    
}


+(NSURLSessionDataTask *)uploadImage:(NSString *)url imageFilePath:(NSString *)iamgePath authCode:(NSString *)authCode params:(NSDictionary *)params success:(void (^)(id))success failure:(void (^)(NSError *))failure{
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/html", nil];
    [manager.requestSerializer setValue:authCode forHTTPHeaderField:@"auth"];
    
    NSURLSessionDataTask *dataTask = [manager POST:url parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        
        [formData appendPartWithFileURL:[NSURL fileURLWithPath:iamgePath] name:@"imgFile" error:nil];
        
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        if (success) {
            success(responseObject);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (failure) {
            failure(error);
        }
    }];
    
    return dataTask;
    
}




/**
 url中带参数  params 不带参数的 GET 网络请求
 
 @param url 请求的url
 @param success 成功block
 @param failure 失败block
 @return nil
 */
+(NSURLSessionDataTask *)get:(NSString *)url success:(void (^)(id))success failure:(void (^)(NSError *))failure
{
    //url = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    

    url = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    //1.获得请求管理者
    AFHTTPSessionManager *mgr = [AFHTTPSessionManager manager];
    mgr.requestSerializer = [AFJSONRequestSerializer serializer];
    mgr.responseSerializer = [AFJSONResponseSerializer serializer];
    mgr.requestSerializer.timeoutInterval = 15;
    mgr.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/plain", @"text/html", nil];
    [mgr.requestSerializer setValue:@"application/x-www-form-urlencoded; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
    
    
    NSURLSessionDataTask *dataTask = [mgr GET:url parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        [MBProgressHUD hideHUD];
        if (success) {
            success(responseObject);
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        [MBProgressHUD hideHUD];
        if (failure) {
            failure(error);
        }
    }];
    
    return dataTask;
}





+ (void)DownLoadFileWithUrlStr:(NSString *)UrlStr FileName:(NSString *)FileName Path:(NSString *)Path Progress:(void(^)(CGFloat))Progress Complete:(void(^)(NSString *FullPath,NSError *Err))Complete
{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    NSURL *url = [NSURL URLWithString:UrlStr];
    
    
    
    
    
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    /*
     第一个参数:请求对象
     第二个参数:progress 进度回调
     第三个参数:destination--(downloadTask-)
     在该block中告诉AFN应该把文件存放在什么位置,AFN内部会自动的完成文件的剪切处理
     targetPath:文件的临时存储路径(tmp)
     response:响应头信息
     返回值:文件的最终存储路径
     第四个参数:completionHandler 完成之后的回调
     filePath:文件路径 == 返回值
     */
    NSURLSessionDownloadTask *download = [manager downloadTaskWithRequest:request progress:
                                          ^(NSProgress * _Nonnull downloadProgress) {
                                              
                                              //进度回调,可在此监听下载进度(已经下载的大小/文件总大小)
                                              Progress (1.0 * downloadProgress.completedUnitCount / downloadProgress.totalUnitCount);
                                              
                                          } destination:^NSURL * _Nonnull(NSURL * _Nonnull
                                                                          targetPath, NSURLResponse * _Nonnull response) {
                                              NSFileManager *fileManeger = [NSFileManager defaultManager];
                                              if (![fileManeger fileExistsAtPath:Path])
                                              {
                                                  [fileManeger createDirectoryAtPath:Path
                                                         withIntermediateDirectories:YES
                                                                          attributes:nil
                                                                               error:nil];
                                              }
                                              //存储路径
                                              return [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/%@",Path,FileName]];
                                              
                                          } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath,
                                                                NSError * _Nullable error) {
                                              
                                              //下载成功返回保存的路径
                                              NSLog(@"%@",(NSString *)filePath);
                                              Complete ((NSString *)filePath,error);
                                              
                                          }];
    
    [download resume];
}


+ (void)SessGet:(NSString *)url authCode:(NSString *)authCode params:(NSDictionary *)params success:(void (^)(id))success failure:(void (^)(NSError *))failure
{


    NSArray *KeyArr = [params allKeys];
    NSArray *ValueArr = [params allValues];
    for (int i=0; i<KeyArr.count; i++)
    {
        NSString *Key = KeyArr[i];
        NSString *Value = ValueArr[i];
        if (i==0)
        {
            url = [NSString stringWithFormat:@"%@%@=%@",url,Key,Value];
        }
        else
        {
            url = [NSString stringWithFormat:@"%@&%@=%@",url,Key,Value];
        }
    }
    url = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

    NSURL *URL = [NSURL URLWithString:url];
    NSMutableURLRequest *Request = [NSMutableURLRequest requestWithURL:URL];
    [Request addValue:authCode forHTTPHeaderField:@"auth"];
    NSURLSessionConfiguration *Con = [NSURLSessionConfiguration defaultSessionConfiguration];
    NSURLSession *Session = [NSURLSession sessionWithConfiguration:Con];
    NSURLSessionTask *Task = [Session dataTaskWithRequest:Request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {

        dispatch_async(dispatch_get_main_queue(), ^{

            if (error)
            {
                failure (error);
            }
            else
            {
                success (data);
            }
        });
    }];
    [Task resume];
}


+ (void)SessPost:(NSString *)url authCode:(NSString *)authCode params:(NSDictionary *)params success:(void (^)(id))success failure:(void (^)(NSError *))failure
{


    NSArray *KeyArr = [params allKeys];
    NSArray *ValueArr = [params allValues];
    NSMutableArray *Arr = [NSMutableArray array];
    for (int i=0; i<KeyArr.count; i++)
    {
        NSString *Key = KeyArr[i];
        NSString *Value = ValueArr[i];

        [Arr addObject:[NSString stringWithFormat:@"%@=%@",Key,Value]];

    }
    url = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSURL *URL = [NSURL URLWithString:url];
    NSMutableURLRequest *Request = [NSMutableURLRequest requestWithURL:URL];
    [Request addValue:authCode forHTTPHeaderField:@"auth"];
    Request.HTTPBody = [[Arr componentsJoinedByString:@"&"] dataUsingEncoding:NSUTF8StringEncoding];
    Request.HTTPMethod = @"POST";
    NSURLSessionConfiguration *Con = [NSURLSessionConfiguration defaultSessionConfiguration];
    NSURLSession *Session = [NSURLSession sessionWithConfiguration:Con];
    NSURLSessionTask *Task = [Session dataTaskWithRequest:Request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {

        dispatch_async(dispatch_get_main_queue(), ^{

            if (error)
            {
                failure (error);
            }
            else
            {
                success (data);
            }
        });
    }];
    [Task resume];
}
@end
